<?php

namespace app\admin\controller\activityform;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use app\admin\model\activityform\Fromurlque;
use think\Db;

/**
 * 表单url
 *
 * @icon fa fa-circle-o
 */
class Fromurl extends Backend
{

    /**
     * Fromurl模型对象
     * @var \app\admin\model\Fromurl
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\activityform\Fromurl;
        $this->view->assign("stateList", $this->model->stateList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            $modelque = new \app\admin\model\activityform\Fromurlque;
            //变数字为对应name
            $allData = $modelque->field('id,name')->select();
            $tmpArray = array();
            foreach ($allData as $v) {
                $tmpArray[$v['id']] = $v['name'];
            }

            foreach ($list as &$v) {
                if (!empty($v['fromurlques_ids'])) {
                    $explodeArray = explode(',', $v['fromurlques_ids']);
                    if (count($explodeArray) == 1) {
                        $v['fromurlques_ids'] = $tmpArray[$v['fromurlques_ids']];
                    } else {
                        $v['fromurlques_ids'] = '';
                        foreach ($explodeArray as $explodeArrayV) {
                            $v['fromurlques_ids'] = $v['fromurlques_ids'] . $tmpArray[$explodeArrayV] . ',';
                        }
                        $v['fromurlques_ids'] = substr($v['fromurlques_ids'], 0, -1);
                    }
                }
            }
            unset($v);

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }



    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params) {
                    //验证标识码唯一性
                    $result = $this->validate($params, 'app\admin\validate\activityform\Fromurl');
                    if (true !== $result) {
                        // 验证失败 输出错误信息
                        $this->error($result);
                    }

                    //判断[选择题目]中有没有重复的
                    if (!empty($params['fromurlques_ids'])) {
                        $retArr = [];
                        foreach (explode(',', $params['fromurlques_ids']) as $eid) {
                            $retArrTmp = [];
                            $this->getAllSon($eid, $retArrTmp);
                            $retArr = array_merge($retArr, $retArrTmp);
                        }
                        // 获取去掉重复数据的数组
                        $unique_arr = array_unique($retArr);
                        // 获取重复数据的数组
                        $repeat_arr = array_diff_assoc($retArr, $unique_arr);
                        if (!empty($repeat_arr)) {
                            $retStr = [];
                            foreach ($repeat_arr as $repeat_arr_v) {
                                $rep = Fromurlque::get($repeat_arr_v);
                                array_push($retStr, '题目' . $rep['id'] . ":" . $rep['name']);
                            }
                            $this->error(implode('  ', array_unique($retStr)) . "重复出现,一个题目(包括其关联的题目)在一个表单中只能出现一次,如您需要请新建题目", null, '', 5);
                        }
                    }
                    $sn = $params['sn'];
                    $params['url'] = '/index.php/addons/activityform/aform?sn=' . $sn;
                    $this->model->create($params);
                    $this->code = 1;
                    return $this;
                }
                AdminLog::record(__('Add'), $this->model->getLastInsID());
                $this->code = 1;
            }
            $this->code = 1;
            return $this;
        }
        return $this->view->fetch();
    }

    public function edit($ids = '')
    {

        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params) {
                    $sn = $params['sn'];
                    $params['url'] = '/index.php/addons/activityform/aform?sn=' . $sn;
                    $this->model->update($params, ['id' => $ids]);
                    $this->code = 1;
                    return $this;
                }
                AdminLog::record(__('Add'), $this->model->getLastInsID());
                $this->code = 1;
            }
            $this->code = 1;
            return $this;
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    private function getAllSon($id, &$retArr = [])
    {
        array_push($retArr, $id);
        $que = Fromurlque::get($id);

        if ($que['type'] == 'radio') {
            $queSonList = Fromurlque::all(['pid' => $id]);
            foreach ($queSonList as $queSonListV) {
                $queSonListSon = Fromurlque::all(['pid' => $queSonListV->id]);
                foreach ($queSonListSon as $queSonListSonV) {
                    $this->getAllSon($queSonListSonV->id, $retArr);
                }
            }
        }
    }

}
